import { useContext, useEffect, useState } from 'react'
import { compile } from './compiler'
import { PlaygroundContext } from '../../ReactPlayground/PlaygroundContext'
import Editor from '../CodeEditer/Editor'
import iframeRaw from './iframe.html?raw'
import {IMPORT_MAP_FILE_NAME} from '../../ReactPlayground/files'
export default function Perview() {
  const { files } = useContext(PlaygroundContext)
  const [code,setCode]=useState('')
  const getIframeUrl=()=>{
    const res=iframeRaw.replace(
      // 替换importmap,将react路径对象添加进去
      '<script type="importmap"></script>',
      `<script type="importmap">
        ${files[IMPORT_MAP_FILE_NAME].value}
      </script>`,
    ).replace(
      // 替换module,将mian文件编译后的代码添加进去
      '<script type="module"></script>',
      `<script type="module">
        ${code}
      </script>`,
    )
    return URL.createObjectURL(new Blob([res], { type: 'text/html' }))
  }
  const [iframeUrl,setIframeUrl]=useState(getIframeUrl())
  useEffect(()=>{
    setCode(compile(files) as string)
  },[files])
  useEffect(()=>{
    setIframeUrl(getIframeUrl())
  },[code])
  // useEffect(()=>{
  //   const newIframeUrl=getIframeUrl()
  //   setIframeUrl(newIframeUrl)
  //   return ()=>{
  //     URL.revokeObjectURL(newIframeUrl)
  //   }
  // },[files])
  return (
    <div style={{ height: '100%' }}>
      <div>
        <button onClick={()=>{
          setIframeUrl(getIframeUrl())
        }}>刷新</button>
      </div>
      <iframe 
        src={iframeUrl} 
        style={{width:'100%',height:'100%',padding:0,border:0}}>
      </iframe>
      {/* <Editor file={{
        name: 'preview',
        language: 'javascript',
        value: code
      }} onChange={() => {}} /> */}
    </div>
  )
}